package com.kinon.ogt.view.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kinon.ogt.GlideApp;
import com.kinon.ogt.R;
import com.kinon.ogt.api.OgtApi;
import com.kinon.ogt.api.exception.ApiException;
import com.kinon.ogt.api.service.ServiceFactory;
import com.kinon.ogt.model.User;
import com.kinon.ogt.model.UserInfo;
import com.kinon.ogt.utils.RxUtils;
import com.kinon.ogt.utils.SPrefsUtils;
import com.kinon.ogt.utils.StringUtils;
import com.kinon.ogt.utils.ToastUtils;
import com.kinon.ogt.view.activities.MainActivity;
import com.kinon.ogt.view.activities.ShareActivity;
import com.kinon.ogt.view.activities.SignInActivity;
import com.kinon.ogt.view.activities.UserInfoActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.disposables.Disposable;

/**
 * 佛祖保佑 永无BUG
 *
 * @author WangZhiYao
 * @date 2018/4/25
 */
public class UserFragment extends Fragment {

    private static final int REQUEST_CODE = 0;

    @BindView(R.id.iv_user_avatar)
    ImageView mIvAvatar;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.tv_user_phone)
    TextView mTvUserPhone;
    @BindView(R.id.tv_user_ogt)
    TextView mTvUserOgt;
    @BindView(R.id.tv_user_degree)
    TextView mTvUserDegree;

    private Unbinder mUnBinder;
    private Disposable mDisposable;

    private String mToken;
    private OgtApi mOgtApi;
    private User mUser;

    private MainActivity mMainActivity;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_user, container, false);
        mUnBinder = ButterKnife.bind(this, rootView);

        initData();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            refreshUserInfo();
        }
    }

    private void initData() {
        mToken = SPrefsUtils.readToken();
        mOgtApi = ServiceFactory.getOgtApi();
    }

    private void refreshUserInfo() {
        mDisposable = mOgtApi.getUserInfo(mToken)
                .compose(RxUtils.rxSchedulerHelper())
                .compose(RxUtils.handleResult())
                .subscribe(this::initView, throwable ->
                        ToastUtils.showShort(mMainActivity, ((ApiException) throwable).getMsg()));
    }

    private void initView(UserInfo userInfo) {
        if (null != userInfo.getUser()) {
            mUser = userInfo.getUser();

            GlideApp.with(mMainActivity)
                    .load(mUser.getPic())
                    .into(mIvAvatar);

            mTvUserName.setText(mUser.getName());
            mTvUserPhone.setText(StringUtils.convertWithMosaic(mUser.getPhone()));
            mTvUserOgt.setText(mUser.getOgc());
            mTvUserDegree.setText(String.valueOf(mUser.getDegree()));
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) context;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnBinder.unbind();
    }

    @OnClick({R.id.rl_user_info, R.id.rl_props_exchange, R.id.rl_ogt_exchange, R.id.rl_invite_friends, R.id.rl_sign_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_user_info:
                sendUserInfo();
                break;
            case R.id.rl_props_exchange:
                ToastUtils.showShort(mMainActivity, "暂未开放，敬请期待");
                break;
            case R.id.rl_ogt_exchange:
                ToastUtils.showShort(mMainActivity, "暂未开放，敬请期待");
                break;
            case R.id.rl_invite_friends:
                shareToFriends();
                break;
            case R.id.rl_sign_out:
                showSignOutDialog();
                break;
            default:
                break;
        }
    }

    private void sendUserInfo() {
        Intent intent = new Intent(mMainActivity, UserInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("USER", mUser);
        intent.putExtras(bundle);
        startActivityForResult(intent, REQUEST_CODE);
    }

    private void shareToFriends() {
        Intent intent = new Intent(UserFragment.this.getActivity(), ShareActivity.class);
        intent.putExtra("TOKEN", mToken);
        startActivity(intent);
    }

    private void showSignOutDialog() {
        new AlertDialog.Builder(mMainActivity)
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    SPrefsUtils.clear();
                    startActivity(new Intent(mMainActivity, SignInActivity.class));
                    mMainActivity.finish();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @OnClick(R.id.iv_user_name_edit)
    public void onUserNameEditClicked() {
        View dialogView = LayoutInflater.from(mMainActivity).inflate(R.layout.dialog_edit, null);
        EditText etEdit = dialogView.findViewById(R.id.et_edit);
        new AlertDialog.Builder(mMainActivity)
                .setTitle("修改昵称")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    String name = etEdit.getText().toString();
                    updateUserInfo(name);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void updateUserInfo(String name) {
        mDisposable = mOgtApi.updateUserInfo(mToken, name)
                .compose(RxUtils.rxSchedulerHelper())
                .subscribe(baseResponse -> {
                    if (baseResponse.isCode()) {
                        ToastUtils.showShort(mMainActivity, baseResponse.getMsg());
                        refreshUserInfo();
                    }
                });
    }

    @OnClick(R.id.btn_user_withdrawals)
    public void onUserWithdrawalsClicked() {
        ToastUtils.showShort(mMainActivity, "暂未开放，敬请期待");
    }

    @OnClick(R.id.btn_user_recharge)
    public void onUserRechargeClicked() {
        ToastUtils.showShort(mMainActivity, "暂未开放，敬请期待");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE == requestCode && resultCode == REQUEST_CODE) {
            refreshUserInfo();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mDisposable) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
